<template>
  <div class="main user-layout-register">
    <h3><span>用户注册</span></h3>
    <a-form ref="formRegister" :form="form" id="formRegister" @submit="handleSubmit">
      <!--      邮箱-->
      <a-form-item>
        <a-input
            size="large"
            type="text"
            placeholder="请输入邮箱"
            v-decorator="[
                'email',
                {rules: [
                    { required: true, message: '邮箱为必填项'},
                    { type: 'email', message: '请输入正确的邮箱'},
                    { validator: checkEmailHandler }], validateTrigger: ['change', 'blur']}]"
        ></a-input>
      </a-form-item>
      <!--      登录名-->
      <a-form-item>
        <a-input
            size="large"
            type="text"
            placeholder="请输入登录名"
            v-decorator="[
                'username',
                {rules: [
                    { required: true, message: '登录名为必填项' },
                    { validator: checkUsernameHandler }], validateTrigger: ['blur']}]"
        ></a-input>
      </a-form-item>
      <!--      密码-->
      <a-popover
          placement="rightTop"
          :trigger="['focus']"
          :getPopupContainer="(trigger) => trigger.parentElement"
          v-model="state.passwordLevelChecked">
        <template slot="content">
          <div :style="{ width: '240px' }" >
            <div :class="['user-register', passwordLevelClass]">{{ passwordLevelName }}</div>
            <a-progress :percent="state.percent" :showInfo="false" :strokeColor=" passwordLevelColor " />
            <div style="margin-top: 10px;">
              <span>密码安全提示</span>
            </div>
          </div>
        </template>
        <a-form-item>
          <a-input-password
              size="large"
              @click="handlePasswordInputClick"
              placeholder="请输入密码"
              v-decorator="[
                  'password',
                  {rules: [
                      { required: true, message: '密码为必填项' },
                      { validator: handlePasswordLevel }], validateTrigger: ['change', 'blur']}]"
          ></a-input-password>
        </a-form-item>
      </a-popover>

      <a-form-item>
        <a-input-password
            size="large"
            placeholder="请再次输入密码"
            v-decorator="[
                'password2',
                {rules: [
                    { required: true, message: '确认密码为必填项' },
                    { validator: handlePasswordCheck }], validateTrigger: ['change', 'blur']}]"
        ></a-input-password>
      </a-form-item>
      <!--      验证码-->
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="16">
          <a-form-item>
            <a-input size="large" type="text" placeholder="请输入邮箱验证码"
                     v-decorator="[
                         'captcha',
                         {rules: [
                             { required: true, message: '邮箱验证码为必填项' }
                             ], validateTrigger: 'blur'}]">
              <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-button
              class="getCaptcha"
              size="large"
              :disabled="state.smsSendBtn"
              @click.stop.prevent="getCaptcha"
              v-text="!state.smsSendBtn && '发送验证码' || (state.time+' s')"></a-button>
        </a-col>
      </a-row>
      <!--      用户注册-->
      <a-form-item>
        <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="register-button"
            :loading="registerBtn"
            :disabled="registerBtn">
          注册账号
        </a-button>
        <router-link class="login" :to="{ name: 'login' }">已有账号,去登陆</router-link>
      </a-form-item>

    </a-form>
  </div>
</template>

<script>
const levelNames = {
  0: '密码强度太低',
  1: '密码强度低',
  2: '密码强度中等',
  3: '密码强度安全'
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success'
}
const levelColor = {
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#52c41a'
}

import { scorePassword } from '@/utils/util'
import {checkEmailExist, checkUserNameExist, userRegister} from '@/api/user'
import { getCaptcha } from '@/api/base'
export default {
  name: 'Register',
  data () {
    return {
      form: this.$form.createForm(this),

      state: {
        time: 60,
        level: 0,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      registerBtn: false
    }
  },
  computed: {
    passwordLevelClass () {
      return levelClass[this.state.passwordLevel]
    },
    passwordLevelName () {
      return levelNames[this.state.passwordLevel]
    },
    passwordLevelColor () {
      return levelColor[this.state.passwordLevel]
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'register' });
  },
  methods: {
    // 提示等级
    handlePasswordLevel (rule, value, callback) {
      if (value === '') {
        return callback('密码为必填项')
      }
      if (value.length >= 6) {
        if (scorePassword(value) >= 30) {
          this.state.level = 1
        }
        if (scorePassword(value) >= 60) {
          this.state.level = 2
        }
        if (scorePassword(value) >= 80) {
          this.state.level = 3
        }
      } else {
        this.state.level = 0
        callback(new Error('密码强度提示'))
      }
      this.state.passwordLevel = this.state.level
      this.state.percent = this.state.level * 33

      callback()
    },

    handlePasswordCheck (rule, value, callback) {
      const password = this.form.getFieldValue('password')
      if (value === undefined) {
        callback(new Error('确认密码为必填项'))
      }
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error('两次密码不一致'))
      }
      callback()
    },

    handlePasswordInputClick () {
      if (!this.isMobile) {
        this.state.passwordLevelChecked = true
        return
      }
      this.state.passwordLevelChecked = false
    },
    // 检查邮箱
    checkEmailHandler(rule, value, callback) {
      if (value === '' || value === undefined) {
        return callback()
      } else {
        checkEmailExist(value).then(res => {
          const {code, data} = res;
          if (code === 200) {
            if (data > 0) {
              callback(new Error(value + '已存在'))
            } else {
              callback()
            }
          }
        }).catch(() => {
          this.$message.error('请求发送失败');
        })
      }
    },

    // 验证用户名
    checkUsernameHandler(rule, value, callback){
      if (value === '' || value === undefined) {
        return callback()
      } else{
        checkUserNameExist(value).then(res => {
          const { code,data } = res;
          if (code === 200){
            if (data > 0){
              callback(new Error(value + '已存在'))
            }else{
              callback()
            }
          }
        }).catch(() => {
          this.$message.error('请求发送失败');
        })
      }
    },
    // 用户注册
    handleSubmit (e) {
      e.preventDefault();
      this.form.validateFieldsAndScroll(async (err, values) => {
        if (!err) {
          const result = await userRegister(values);
          if(result.code === 200){
            this.state.passwordLevelChecked = false
            this.$router.push({ name: 'registerResult', params: { ...values } })
            this.$notification['success']({
              message: '提示',
              description: result.msg,
              duration: 8
            })
          }else{
            this.$notification['error']({
              message: '提示',
              description: result.msg,
              duration: 8
            })
          }
        }else{
          this.$message.error('检验不通过');
        }
      });
    },
    // 获取验证码
    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state} = this

      validateFields(['email'], { force: true }, async (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)

          // 获取验证码
          getCaptcha(values.email).then(res => {
            if (res.code === 200){
              setTimeout(hide, 2500)
              this.$notification['success']({
                message: '提示',
                description: '验证码获取成功,请查收',
                duration: 8
              })
            }else{
              this.$notification['error']({
                message: '提示',
                description: res.msg,
                duration: 8
              })
            }
          }).catch(err => {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.time = 60
            state.smsSendBtn = false
            this.requestFailed(err)
          })
        }
      })
    },
    requestFailed (err) {
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.registerBtn = false
    }
  },
  watch: {
    'state.passwordLevel' (val) {

    }
  }
}
</script>
<style lang="less">
  .user-register {

    &.error {
      color: #ff0000;
    }

    &.warning {
      color: #ff7e05;
    }

    &.success {
      color: #52c41a;
    }

  }

  .user-layout-register {
    .ant-input-group-addon:first-child {
      background-color: #fff;
    }
  }
</style>
<style lang="less" scoped>
  .user-layout-register {

    & > h3 {
      font-size: 16px;
      margin-bottom: 20px;
    }

    .getCaptcha {
      display: block;
      width: 100%;
      height: 40px;
    }

    .register-button {
      width: 50%;
    }

    .login {
      float: right;
      line-height: 40px;
    }
  }
</style>
